<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>143_练习_自动切换图片</title>
	</head>
	<style>
		.outter {
			width: 640px;
			margin: 50px auto;
			text-align: center;
		}
	</style>
	<body>
		<div class="outter">
			<div class="image-wrapper">
				<p></p>
				<img id="image" src="images/1.png" alt="这是一张图片" />
			</div>
			<div class="btn-wrapper">
				<button id="btn-pre" type="button">上一张</button>
				<button id="btn-next" type="button">下一张</button>
			</div>
		</div>
		<script>
			let pre = document.getElementById("btn-pre");
			let next = document.getElementById("btn-next");
			let image = document.getElementById("image")
			let pLable = document.getElementsByTagName("p")[0];


			let arr = ["images/1.png", "images/2.png", "images/3.png", "images/4.png", "images/5.png"]
			pLable.textContent = `共${arr.length}图片，当前是第${1}张`
			pre.addEventListener("click", function() {
				//如何修改iamge src属性，简单一点：image.src或者src.attributes
				let index = imageIndex(image.src)
				index--;
				if (index < 0) {
					index = 4;
				}
				pLable.textContent = `共${arr.length}图片，当前是第${index+1}张`
				image.src = arr[index]
			})
			next.addEventListener("click", function() {
				let index = imageIndex(image.src)
				index++;
				if (index > 4) {
					index = 0;
				}
				pLable.textContent = `共${arr.length}图片，当前是第${index+1}张`
				image.src = arr[index]
			})

			setInterval(() => {
				let index = imageIndex(image.src)
				index++;
				if (index > 4) {
					index = 0;
				}
				pLable.textContent = `共${arr.length}图片，当前是第${index+1}张`
				image.src = arr[index]
			}, 3000)

			function imageIndex(curr) {
				if (curr.endsWith("1.png")) {
					return 0;
				} else if (curr.endsWith("2.png")) {
					return 1;
				} else if (curr.endsWith("3.png")) {
					return 2;
				} else if (curr.endsWith("4.png")) {
					return 3;
				} else if (curr.endsWith("5.png")) {
					return 4;
				} else {
					-1;
				}

			}
		</script>
	</body>
</html>